/**
 * Project  : Looker
 * Package  : net.freestu.looker.monitor
 * File     : ContentUpdater.java
 * Author   : solosky < solosky772@qq.com >
 * Date     : Aug 27, 2009
 * Modified : Aug 27, 2009
 * License  : Apache License 2.0 
 */
package net.freestu.looker.monitor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.log4j.Logger;

import net.freestu.looker.common.Category;
import net.freestu.looker.common.Looker;
import net.freestu.looker.common.NewsEntity;
import net.freestu.looker.common.NewsMeta;

/**
 *  新闻正文更新器
 */
public class ContentUpdater extends AbstractMonitor
{
	
	/**
	 * 分析后的新闻信息列表
	 */
	private ArrayList<NewsEntity> newsEntityList;
	
	/**
	 * 日志记录
	 */
	private static Logger logger = Logger.getLogger(ContentUpdater.class);
	/**
	 * 构造函数
     * @param category
     */
    public ContentUpdater(Category category)
    {
	    super(category);
	    this.newsEntityList = new ArrayList<NewsEntity>();
    }

	/* (non-Javadoc)
	 * @see net.freestu.looker.monitor.AbstractMonitor#start()
	 */
	@Override
	public void start()
	{
		synchronized (category) {	        
    		try {
    			logger.info(this+"开始检查..");
    	        fetchContent();
    			parseContent();
    			checkModify();
    			finish();
    			logger.info(this+"完成检查.");
            } catch (Exception e) {
            	logger.warn(this+"出错："+e.getMessage());
            	e.printStackTrace();
            }
        }

	}
	
	/**
	 * 获取当前临时新闻列表新闻正文
	 * @throws IOException 
	 * @throws FetcherException 
	 * @throws InterruptedException 
	 */
	private void fetchContent() throws IOException, FetcherException, InterruptedException
	{
		//读取之前的新闻列表
		category.getListManager().readBeforeList();
		Iterator<NewsMeta> bit = category.getListManager().getBeforeList().iterator();
		//根据之前的新闻列表下载新闻正文
		ArrayList<HtmlFetcher> fetcherList = new ArrayList<HtmlFetcher>();
		FetcherGroup fetcherGroup = new FetcherGroup();
		HtmlFetcher fetcher = null;
		while(bit.hasNext())
		{
			fetcher = new HtmlFetcher(bit.next().getUrl());
			fetcherGroup.addFetcher(fetcher);
			fetcherList.add(fetcher);
		}
		//启动下载组，并等待下载完成
		fetcherGroup.start();
		fetcherGroup.await();
		
		//TODO..检查是否都是下载完成的
		
		//获取下载的新闻正文HTML
		Iterator<HtmlFetcher> fit = fetcherList.iterator();
		NewsEntity newsEntity = null;
		while(fit.hasNext()) {
			fetcher = fit.next();
			if(fetcher.isSuccess()) {
				newsEntity = new NewsEntity();
				newsEntity.setUrl(fetcher.getUrl());
				newsEntity.setHtml((String) fetcher.getFeched());
				newsEntity.setCategory(category);
				
				newsEntityList.add(newsEntity);
			}
		}
	}
	
	/**
	 * 分析新闻正文
	 */
	private void parseContent()
	{
		Iterator<NewsEntity> it = newsEntityList.iterator();
		ContentParser parser = null;
		while(it.hasNext()) {
			parser = new ContentParser(it.next());
			parser.parse();
		}
	}
	
	/**
	 * 检查更新
	 * @throws IOException 
	 */
	private void checkModify() throws IOException
	{
		ArrayList<NewsMeta> tmpList = new ArrayList<NewsMeta>();
		Iterator<NewsEntity> it = newsEntityList.iterator();
		while(it.hasNext()) {
			tmpList.add(it.next().toNewsMeta());
		}
		NewsMetaListManager listManager = category.getListManager();
		listManager.readBeforeList();
		listManager.setCurrentList(tmpList);
    	listManager.updateCurrentList(false, true);
    	listManager.checkModify();
    	listManager.saveCurrentList();
	}

	/* (non-Javadoc)
     * @see net.freestu.looker.monitor.AbstractMonitor#finish()
     */
    @Override
    public void finish()
    {
    	Looker.contentUpdaterScheduler.finish(category);
    }
    
    public String toString()
    {
    	return "新闻更新器 - ["+category.getTitle()+"|"+category.getHash()+"] - ";
    }

}
